package com.adserver.adview;

import org.apache.http.client.ClientProtocolException;

import java.io.File;
import java.io.IOException;
import java.util.logging.Level;

public class ContentThread extends Thread {
    private static final String FIRST_APP_LAUNCH_URL = "http://www.moceanmobile.com/appconversion.php";
    private static final String FIRST_APP_LAUNCH_FILE_NAME = "mojiva_first_run_application.tmp";

    private AdServerView adServerView;
    private boolean isRepeat = true;

    public ContentThread(AdServerView adServerView, boolean isRepeat) {
        this.adServerView = adServerView;
        this.isRepeat = isRepeat;
    }

    @Override
    public void run() {
        Logger.getInstance().logText(Level.INFO, "runContentThread from ContentThread");
        runContentThread(adServerView, isRepeat);
    }

    public static void runContentThread(AdServerView adServerView, boolean isRepeat) {
        clientInitialization(adServerView);

        boolean isShownView = adServerView.isActivatedComponent();
        Logger.getInstance().logText(Level.INFO, "runContentThread, adServerView.isVisible(): " + isShownView);

        String data;

        if (isShownView) {
            if (adServerView.isFirstRun()) {
                try {
                    String imgSrc;
                    if (adServerView.getDefaultImage() != null && adServerView.getDefaultImage().length() > 0) {
                        imgSrc = adServerView.getClass().getClassLoader().getResource(adServerView.getDefaultImage()).toString();
                    } else {
                        imgSrc = adServerView.getClass().getClassLoader().getResource("images/wait.gif").toString();
                    }
                    adServerView.showAdContent("<html><img src='" + imgSrc + "' />");
                } catch (Exception e) {
                    Logger.getInstance().logText(Level.SEVERE, "Error with default image show", e);
                }
                adServerView.setFirstRun(false);
            }

            try {
                if (adServerView.getAdDownload() != null) {
                    adServerView.getAdDownload().begin();
                }

                data = AdServerRequest.getInstance().processGetRequestEx(adServerView.createURL());
                Logger.getInstance().logText(Level.INFO, "Data for processGetRequestEx: " + data);


                if (data.indexOf("<!-- invalid params -->") != -1) {
                    adServerView.getAdDownload().error(data);
                } else {
                    if (adServerView.getAdDownload() != null) {
                        adServerView.getAdDownload().end();
                    }
                    if ((data != null) && (data.length() > 0)) {
                        data = "<html><head/><body style=\"margin: 0px; padding: 0px;\">" +
                                data + "</body></html>";
                        adServerView.showAdContent(data);
                    }
                }
            } catch (IOException e) {
                if (adServerView.getAdDownload() != null) {
                    adServerView.getAdDownload().error(e.getMessage());
                }
                Logger.getInstance().logText(Level.SEVERE,
                        "AdServerRequest.getInstance().processGetRequestEx: " + e.getMessage());
            }
        }

        if (isRepeat) {
            adServerView.initializeReloadTask();
        }
    }

    private static void clientInitialization(AdServerView adServerView) {
        if ((adServerView.getAdvertiserId() != null) && (adServerView.getAdvertiserId().length() > 0)
                && (adServerView.getGroupCode() != null) && (adServerView.getGroupCode().length() > 0)) {
            String filePath = System.getProperty("java.io.tmpdir") + FIRST_APP_LAUNCH_FILE_NAME;
            File file = new File(filePath);
            if (!file.exists()) {
                StringBuilder url = new StringBuilder(FIRST_APP_LAUNCH_URL);
                url.append("?" + adServerView.parameter_advertiser_id + "=").append(adServerView.getAdvertiserId());
                url.append("&" + adServerView.parameter_group_code + "=").append(adServerView.getGroupCode());
                url.append("&" + adServerView.parameter_device_id + "=").append(adServerView.udid);

                Logger.getInstance().logText(Level.INFO, "URL in clientInitialization: " + url);

                try {
                    String responseBody = AdServerRequest.getInstance().processGetRequest(url.toString());

                    if (responseBody.indexOf("<result>OK</result>") == -1) {
                        Logger.getInstance().logText(Level.SEVERE,
                                "Error in clientInitialization" +
                                        ", getAdvertiserId " + adServerView.getAdvertiserId() +
                                        ", getGroupCode" + adServerView.getGroupCode());
                    } else {
                        Logger.getInstance().logText(Level.INFO,
                                "OK in clientInitialization" +
                                        ", getAdvertiserId " + adServerView.getAdvertiserId() +
                                        ", getGroupCode" + adServerView.getGroupCode());
                    }
                } catch (ClientProtocolException e) {
                    Logger.getInstance().logText(Level.SEVERE, "ClientProtocolException in clientInitialization", e);
                } catch (IOException e) {
                    Logger.getInstance().logText(Level.SEVERE, "IOException in clientInitialization", e);
                }

                try {
                    file.createNewFile();
                } catch (IOException e) {
                    Logger.getInstance().logText(Level.SEVERE, "IOException in clientInitialization", e);
                }
            }
        }
    }
}